package com.macro.mall.demo.design.pattern.strategy;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Objects;


public class StrategyRegistry {

    private static final String DEFAULT_STRATEGY_ID = "DEFAULT_STRATEGY_ID";
    private static final Map<Class<?>,Map<String, Object>> STRATEGY_MAP = Maps.newConcurrentMap();

    public static Object getStrategyBean(Class<?> strategyInterface, String strategyId) {
        Map<String, Object> strategyMap = STRATEGY_MAP.get(strategyInterface);
        Object strategyBean = strategyMap.get(strategyId);
        if (Objects.isNull(strategyBean)) {
            strategyBean = strategyMap.get(DEFAULT_STRATEGY_ID);
        }
        return strategyBean;
    }

    public static void registerStrategyBean(Class<?> strategyInterface, String strategyId, Object strategyBean) {
        Map<String, Object> strategyMap = STRATEGY_MAP.get(strategyInterface);
        if (Objects.isNull(strategyMap)) {
            strategyMap = Maps.newConcurrentMap();
            STRATEGY_MAP.put(strategyInterface, strategyMap);
        } else if(!strategyMap.containsKey(strategyId)) {
            strategyMap.put(strategyId, strategyBean);
        }
    }


}
